from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.backends import default_backend
import secrets
import base64

class Encryption(object):

    @staticmethod
    def gen_key():
        """生成 16 字节的随机字节串（128-bit）"""
        random_bytes = secrets.token_bytes(16)

        # 将随机字节串转换为十六进制字符串
        random_hex = random_bytes.hex()
        return random_hex;

    @staticmethod
    def aes_encrypt(key, data:str)->str:
        """aes加密
        key: 加密key byte类型
        data: 加密数据
        return : 返回加密的base64字符串
        """
        # 加密数据转字节类型
        encrypt_data = data.encode()
        backend = default_backend()
        iv = b'0123456789abcdef'  # 初始化向量 IV，长度必须为16字节
        cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
        encryptor = cipher.encryptor()
        padder = padding.PKCS7(128).padder()

        padded_data = padder.update(encrypt_data) + padder.finalize()
        ciphertext = encryptor.update(padded_data) + encryptor.finalize()
        # 转base64 字符串
        encoded_data = base64.b64encode(ciphertext).decode('utf-8')
        return encoded_data
    
    @staticmethod
    def aes_decrypt(key, ciphertext:str)->str:
        """aes加密
        key: 加密key byte类型
        data: 解密base64字符串
        return : 返回解密后的数据str
        """
        ciphert_b = base64.b64decode(ciphertext)
        backend = default_backend()
        iv = b'0123456789abcdef'  # 初始化向量 IV，与加密时保持一致
        cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
        decryptor = cipher.decryptor()
        unpadder = padding.PKCS7(128).unpadder()

        padded_data = decryptor.update(ciphert_b) + decryptor.finalize()
        decrypted_data = unpadder.update(padded_data) + unpadder.finalize()

        return decrypted_data.decode('utf-8')
